#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>

#include "log.hpp"

#define PATHNAME "/home/lzh"
#define PROJ_ID 0x123

class sharedMem {
public:
    sharedMem(const string& path_name = PATHNAME, int proj_id = PROJ_ID) :_path_name(path_name), _proj_id(proj_id) {
       _k = ftok(_path_name.c_str(), _proj_id);
       if(_k == -1) {
           perror("ftok err");
           exit(-1);
       }
    }
    int creatShm(size_t size) const {
        int shmid = shmget(_k, size, IPC_CREAT | 0666);
        if(shmid == -1) {
            perror("creat shmget err");
            exit(-1);
        }
        return shmid;
    }
    
    int getShm(size_t size) const  {
        int shmid = shmget(_k, size, IPC_CREAT);
        if(shmid == -1) {
            perror("get shmget err");
            exit(-1);
        }
        return shmid;
    }

    void* setShmat(int shmid, const void* shmaddr = NULL, int shmflg = 0) {
        void* addr = shmat(shmid, shmaddr, shmflg);
        if(addr == (void*)-1) {
            perror("set shmat err");
            exit(-1);
        }
        return addr;
    }

    void setShmdt(const void* shmaddr) {
        int ret = shmdt(shmaddr);
        if(ret == -1) {
            perror("sets shmdt err");
            exit(-1);
        }
    }

    void ctrlShm(int shmid, int cmd, struct shmid_ds* s = NULL) const {
        int ret = shmctl(shmid, cmd, s);
        if(ret == -1) {
            perror("ctrlShm err");
            exit(-1);
        }
    }
private:
    key_t _k;
    const string _path_name;
    const int _proj_id;
};

